import { FStore } from "./FStore";
import { Audio } from "./Audio";
import { StoreManager } from "../Managers/StoreManager";

export class AudioStacker extends FStore
{
    public static ClassName:string = "AudioStacker";
    public onComplete:Function;
    private audios:string[] = [];
    private currentAudio:Audio = null;
    private isPlaying:boolean = false;
    private _volume: number = 1;
    public get volume(): number {return this._volume;}
    public set volume(value: number) 
    {
        this._volume = value;
        this.currentAudio&&(this.currentAudio.volume = this._volume);
    }

    /**添加一个声音（注意：相同的声音可以重复添加）**/
    public addAudio(audioName:string):void
    {
        this.audios.push(audioName);
    }
    public play():void
    {
        if(this.isPlaying)return;
        this.isPlaying = true;
        this.playNextSound();
    }
    private playNextSound():void
    {
        if(this.audios.length==0)
        {
            if(this.onComplete!=null)
            {
                if(this.onComplete.length==0)this.onComplete();
                else this.onComplete(this);
            }
            this.clear();
        }else
        {
            this.currentAudio&&this.currentAudio.dispose();
            this.currentAudio = StoreManager.New(Audio);
            this.currentAudio.volume = this.volume;
            this.currentAudio.name = this.audios.shift();
            this.currentAudio.onComplete = this.playNextSound.bind(this);
            this.currentAudio.play();
        }
    }
    public clear():void
    {
        this.isPlaying = false;
        this.currentAudio&&this.currentAudio.dispose();
        this.currentAudio = null;
        this.audios.length = 0;
    }
    public dispose():void
    {
        this.clear();
        this.onComplete = null;
        this.currentAudio = null;
        super.dispose();
    }
}
